import { IApiControl, IRejectType } from './BaseInterface'

/**
 * FormData 参数格式化
 * @param data 参数对象
 * @returns 
 */
export function formdata(data: any): FormData {
    if (data instanceof FormData) return data
    var formdata = new FormData()
    for (let key in data) {
        if (typeof data[key] === 'object' && !(data[key] instanceof File)) {
            formdata.append(key, JSON.stringify(data[key]))
        } else {
            formdata.append(key, data[key])
        }
    }
    return formdata
}
/**
 * queryObject转queryString
 * @param json
 * @returns
 */
export function getQueryString(json: any): string {
    if (!json) return ''
    return Object.keys(json).map(key => {
        if (json[key] === undefined) return ''
        return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    }).join('&')
}
/**
 * 请求错误处理
 * @param apiControl 请求流程控制参数
 * @param tipsContent 提示内容
 */
export function errTips(apiControl: IApiControl, tipsContent: IRejectType): void {
    if (typeof apiControl.tipFn == 'function') {
        apiControl.tip && apiControl.tipFn(tipsContent)
    }
}
/**
 * 简易的hash运算
 * @param str 文本内容
 * @returns 
 */
export function textHax(str: string): string {
    for (var i = 0, num = 0, len = str.length; i < len; i++) {
        num += (str.charCodeAt(i) / (i + 1.3))
    }
    return (+String(num).replace('.', '') - 0).toString(36)
}